package org.wutopia.labcloud.domain.payment.service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wutopia.labcloud.domain.payment.constant.WalletBillType;
import org.wutopia.labcloud.domain.payment.controller.vo.input.PaymentWalletCreateWalletInputVO;
import org.wutopia.labcloud.domain.payment.controller.vo.input.PaymentWalletDepositInputVO;
import org.wutopia.labcloud.domain.payment.dao.PaymentUserWalletBillDao;
import org.wutopia.labcloud.domain.payment.dao.PaymentUserWalletDao;
import org.wutopia.labcloud.domain.payment.dao.entity.PaymentUserWallet;
import org.wutopia.labcloud.domain.payment.dao.entity.PaymentUserWalletBill;
import org.wutopia.labcloud.domain.payment.service.PaymentUserWalletService;

import java.math.BigDecimal;

@Service
@AllArgsConstructor
@Slf4j
public class PaymentUserWalletServiceImpl implements PaymentUserWalletService {

    private PaymentUserWalletDao paymentUserWalletDao;

    private PaymentUserWalletBillDao paymentUserWalletBillDao;

    private PasswordEncoder passwordEncoder;

    @Override
    public void createWallet(PaymentWalletCreateWalletInputVO vo) {

        PaymentUserWallet wallet = new PaymentUserWallet();

        wallet.setUserId(vo.getUserId());
        wallet.setFrozen(new BigDecimal(0));
        wallet.setMoney(new BigDecimal(0));
        wallet.setPayPassword(passwordEncoder.encode(vo.getPayPassword()));

        paymentUserWalletDao.insert(wallet);
    }

    @Override
    @Transactional
    public void deposit(PaymentWalletDepositInputVO vo) throws Exception {

        PaymentUserWallet wallet = paymentUserWalletDao.selectById(vo.getUserWalletId());


        String payPassword = vo.getPayPassword();

        boolean matches = passwordEncoder.matches(payPassword, wallet.getPayPassword());


        if(!matches) {

            throw new Exception("支付密码错误");
        }

        PaymentUserWalletBill bill = new PaymentUserWalletBill();
        bill.setUserId(vo.getUserId());
        bill.setUserWalletId(vo.getUserWalletId());
        bill.setMoney(vo.getMoney());
        bill.setChannelId(vo.getChannelId());



        bill.setChannelType(vo.getChannelType());
        bill.setStatus(WalletBillType.DEPOSIT);
        paymentUserWalletBillDao.insert(bill);

        UpdateWrapper<PaymentUserWallet> uw = new UpdateWrapper<>();

        uw.eq("user_id", vo.getUserId());
        uw.eq("id", vo.getUserWalletId());
        uw.set("money", wallet.getMoney().add(vo.getMoney()));

        paymentUserWalletDao.update(uw);

    }

    @Override
    @Transactional
    public void withdrawal() {

    }
}
